package cn.com.vrv.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.com.vrv.util.DateUtils;
@Controller
@RequestMapping("webupload")
public class WebUploadController {
	 @Value("${upload.path}")
	 private String path;//配置文件上传路径
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,String> returnMap = new HashMap<String,String>();
		 String dateStr = DateUtils.getDate("yyyyMMdd");
		 String tempFileName = DateUtils.getDate("HHmmssSSS");
		 String realPath = path+File.separator+"upload"+File.separator+dateStr;
		 File realPath_dir = new File(realPath);
         if (!realPath_dir.exists()) {
        	 realPath_dir.mkdirs();
         }
        //没有分片
		if (request.getParameter("chunk") == null) {
            String fileName = file.getOriginalFilename();
            File targetFile = new File(realPath+File.separator+tempFileName+ "\\" +fileName);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            
            try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}// 小文件，直接拷贝
            returnMap.put("docUrl","upload"+File.separator+dateStr+File.separator+tempFileName);
            returnMap.put("fileName",fileName);
            return returnMap;
        } else {
            int chunk = Integer.parseInt(request.getParameter("chunk")); // 当前分片
            int chunks = Integer.parseInt(request.getParameter("chunks")); // 分片总计
            String id = request.getParameter("id");
            System.out.println(chunk+"--"+chunks);
            String fileName ="";
			try {
				// 临时存放分片文件目录 定义
				String tempFileDir = realPath+File.separator+id;
				
				System.out.println("临时存放分片文件目录 tempFileDir: "+tempFileDir);
				
				//创建临时存放分片 目录
				File parentFileDir = new File(tempFileDir);
				if (!parentFileDir.exists()) {
					parentFileDir.mkdirs();
				}
				
				fileName = file.getOriginalFilename();
				
				//保存临时文件
				File tempPartFile = new File(parentFileDir, fileName+ "_" + chunk+ ".part");
				FileUtils.copyInputStreamToFile(file.getInputStream(),tempPartFile);
				System.out.println(fileName + "_" + chunk+ ".part 上传完毕"+"共"+chunks+"个");
				
				//判断临时文件是否已经存在
				boolean uploadDone = true;
				for (int i = 0; i < chunks; i++) {
					File partFile = new File(parentFileDir, fileName+ "_" + i+ ".part");
					if (!partFile.exists()) {
						uploadDone = false;
					}
				}
				
				if (uploadDone) {
					
					//生成全新的文件 
					/*String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
			        tempFileName = tempFileName+"."+ext;*/
					File destTempFile = new File(realPath, fileName);
					
					for (int i = 0; i < chunks; i++) {
						File partFile = new File(parentFileDir, fileName + "_"
								+ i + ".part");

						FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);

						FileUtils.copyFile(partFile, destTempfos);

						destTempfos.close();
					}
                    // 得到 destTempFile 就是最终的文件
                    // 添加到文件系统或者存储中
                    // 删除临时目录中的分片文件
                    FileUtils.deleteDirectory(parentFileDir);
                    returnMap.put("docUrl","upload"+File.separator+dateStr+File.separator+tempFileName);
                    returnMap.put("fileName",fileName);
                    return returnMap;
				} else {
					// 临时文件创建失败
					if (chunk == chunks -1) {
						FileUtils.deleteDirectory(parentFileDir);
					}
				}
				 
				 
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return returnMap;
        }
	}
		@RequestMapping(value = "/delete")
		public void delete(String docUrl, HttpServletResponse response) throws IOException {
			System.out.println(docUrl);
			String uploadDir = path+File.separator+"upload"+File.separator;
			String path = uploadDir + docUrl;
			System.out.println(path);
			File file = new File(path);
			if(!file.exists()){
	        	return;
	        }
			file.delete();
		}

    public String StringFilter(String str)throws PatternSyntaxException {
        // 只允许字母和数字
        // String   regEx  =  "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return m.replaceAll("").trim();
    }

   /* @RequestMapping(value = "/download", method = { RequestMethod.POST,RequestMethod.GET })
	public void download(String id,int index,String ieFlag, HttpServletResponse response) throws IOException {
		
		//System.out.println("downloading....................");
		
		//跟用户相关
		String uploadDir = ConfigureVal.getPath()+File.separator+"upload"+File.separator;
		 
		WsxFlowRunLog flowRunLog = runLogService.get(id);
		if(null == flowRunLog){
			return;
		}
		 
		String runLogName = flowRunLog.getFileName();
		String runDocUrl = flowRunLog.getDocUrl();
		String[] runLogNames = runLogName.split(",");
		String[] runDocUrls = runDocUrl.split(",");

		String fileName = runLogNames[index];//当前文件名
		String docUrl = runDocUrls[index];	  //当前文件路径
		BufferedInputStream ins = null;
		OutputStream out = null;

        String delFileStr = "";
		try {
			//response.setHeader("Content-disposition","attachment;filename=" + name);
			//response.setContentType("application/application/octet-stream bin");//text/plain

			//String fileName = flowRunLog.getFileName();
			//String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
			
			String dateStr = DateUtils.getDate("yyyyMMdd");
			String name = dateStr+"_"+fileName;
            //name = StringEscapeUtils.escapeHtml(name);
            //String tempName = name.replaceAll("\"", "\'");
			response.reset();
            response.setHeader("Content-Type","application/octet-stream");
            //response.setHeader("Content-disposition","attachment;filename="+ name);
            if(ieFlag.equalsIgnoreCase("1")){
                response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
            }else{
                response.setHeader("Content-disposition","attachment;filename="+new String(name.getBytes("gb2312"), "ISO8859-1" ));
            }

	        //设置文件ContentType类型，这样设置，会自动判断下载文件类型  
	        response.setContentType("application/application/octet-stream bin");  
	        //设置文件头：下载文件名
	       // response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(flowRunLog.getFileName(), "UTF-8"));
	        
	        //解密
            String fileKey = Global.getConfig("com.wsx.fileUpload.key");
            String destFile = uploadDir + File.separator + docUrl;
            File desctileExt = new File(destFile+".tdes");
            if(desctileExt.exists()){
                FileSecurityUtils fileSecurityUtils = new FileSecurityUtils(fileKey);
                fileSecurityUtils.decrypt(destFile);
            }

            //通过文件路径获得File对象
            File file = new File(destFile);
            if(!file.exists()){
                return;
            }
            ins = new BufferedInputStream(new FileInputStream(file));  
            //通过response获取ServletOutputStream对象
            out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[2048];
            
            while ((len = ins.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
            
          //TODO 延迟一百毫秒，不会write error
			Thread.sleep(100);
            out.flush();

            delFileStr = destFile;

        } catch (Exception e) {
            e.printStackTrace();  
        } finally {
        	if(ins != null) {
        		ins.close();
        	}
        	if(out != null) {
	            out.close();
        	}
        }

        System.out.println("22");
        //删除解密文件
        try{
            String sourceFileStr = delFileStr+".tdes";
            File sourceFile = new File(sourceFileStr);
            if(sourceFile.exists()){
                File del_file = new File(delFileStr);
                del_file.delete();
                System.out.println(del_file.exists());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
	}*/
}